﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;
using Newtonsoft.Json;

namespace LeSoft.Application.Web.Areas.QualificationManage.Controllers
{
    public class RetrialController : MvcControllerBase
    {
        //
        // GET: /QualificationManage/Retrial/Index
        //复审
        private QualificationBillBLL QFBbll = new QualificationBillBLL();
        private MaterialSeedBLL MSbll = new MaterialSeedBLL();
        private MaterialRuleBLL MRbll = new MaterialRuleBLL();
        private QalificationMaterialRuleBLL QMRbll = new QalificationMaterialRuleBLL();
        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "复审首页", "Index")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "复审详情", "Form")]
        public ActionResult Form()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit, "批量审核", "AllForm")]
        public ActionResult AllForm()
        {
            return View();
        }
        #endregion

        #region 获取数据
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "单据状态树", "GetTreeListTojson")]
        public ActionResult GetTreeListTojson()
        {
            string S = "已复审";
            string str = EnumAttribute.GetDescription(QStateEnum.Checked).Substring(6, 5);
            List<TreeStatusEntity> lst = new List<TreeStatusEntity>();
            lst.Add(new TreeStatusEntity("0", EnumAttribute.GetDescription(QStateEnum.All), QStateEnum.All.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), str, QStateEnum.Checked.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), EnumAttribute.GetDescription(QStateEnum.CityChceking), QStateEnum.CityChceking.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), EnumAttribute.GetDescription(QStateEnum.CenterChecking), QStateEnum.CenterChecking.ToString(), 0));
            lst.Add(new TreeStatusEntity(QStateEnum.All.ToString(), S, "YFS", 0));
            lst.Add(new TreeStatusEntity("YFS", EnumAttribute.GetDescription(QStateEnum.CenterChecked), QStateEnum.CenterChecked.ToString(), 0));
            lst.Add(new TreeStatusEntity("YFS", EnumAttribute.GetDescription(QStateEnum.CenterUnChecked), QStateEnum.CenterUnChecked.ToString(), 0));
            lst.Add(new TreeStatusEntity("YFS", EnumAttribute.GetDescription(QStateEnum.ReturnBack), QStateEnum.ReturnBack.ToString(), 0));

            List<TreeEntity> treeList = new List<TreeEntity>();
            foreach (TreeStatusEntity item in lst)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = lst.Count(t => t.PValue == item.Value) == 0 ? false : true;
                tree.id = item.Value;
                tree.text = item.Text;
                tree.value = item.Value;
                if (item.PValue == "0") tree.isexpand = true;
                else tree.isexpand = false;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                tree.parentId = item.PValue;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }
        /// <summary>
        /// 分页获取获取单据列表
        /// </summary>
        /// <param name="type"> 1-初审 2-复审</param>
        /// <param name="pagination">分页参数</param>
        /// <param name="queryJson">  查询参数json:State StartTime EndTime Name IDCard Phone</param>
        /// <returns></returns>
        ///  
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "分页获取获取单据列表", "GetPageList")]
        public ActionResult GetPageList(Pagination pagination, string queryJson)
        {
            var data = QFBbll.GetPageList(2, pagination, queryJson);
            var watch = CommonHelper.TimerStart();
            List<QualificationBillEntity> Lst = data.ToJson().ToObject<List<QualificationBillEntity>>();
            foreach (var a in Lst)
            {
                if (a.ReCheckDay.IsEmpty() || a.ReCheckDay == 0)
                {
                    DateTime? FirstFielTime = null;
                    int Times = -1;
                    IEnumerable<BillOperateRecordEntity> lst = new BillOperateRecordBLL().GetList(a.Id).OrderBy(t => t.Date);
                    var List = lst.FirstOrDefault(e => e.Type.Contains("材料"));
                    if (List != null)
                    {
                        FirstFielTime = List.Date; 
                        if (a.State == 7 && lst.Count(e => e.Type == "复审通过") > 0 && !FirstFielTime.IsEmpty())
                        {
                            a.FirstCheckDate = FirstFielTime;
                            a.CreateDate = lst.First(e => e.Type == "复审通过").Date; 
                            Times = Time.GetWorkerDayNum(a.FirstCheckDate.ToDate(), a.ReCheckDate.ToDate()); 
                        }
                        if ((a.State == 4 || a.State == 5 || a.State == 6) && !FirstFielTime.IsEmpty())
                        {
                            a.FirstCheckDate = FirstFielTime; 
                            Times = Time.GetWorkerDayNum(a.FirstCheckDate.ToDate(), DateTime.Now); 
                        }
                        if (Times == 0) Times = 1;
                        a.ReCheckDay = Times;
                    }
                }

            }
            var JsonData = new
            {
                rows = Lst,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 获取复审详情
        /// </summary>
        /// <param name="keyValue">单据主键</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "申请单实体", "GetEntity")]
        public ActionResult GetEntity(string keyValue)
        {
            var data = QFBbll.GetEntity(keyValue);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取单据信息
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.GetList, "复审详情", "GetBillInfo")]
        public ActionResult GetBillInfo(string keyValue)
        {
            var data = QFBbll.GetBillInfo(keyValue);
            var JSON = data.ToJObject();
            DateTime? FirstFielTime = null;
            var IsShowTime = 0;
            int Times = 0;
            var OperateMemo = "[" + JSON["BillInfo"]["OperateMemo"] + "]";
            int State = JSON["BillInfo"]["State"].ToInt();
            List<OperateMemo> lst = OperateMemo.ToObject<List<OperateMemo>>();
            lst = lst.OrderBy(e => e.Date).ToList();
            if (lst.Count(e => e.Type == "材料通过") > 0) FirstFielTime = lst.First(e => e.Type == "材料通过").Date;
            if (lst.Count(e => e.Type == "递交材料不通过") > 0) FirstFielTime = lst.First(e => e.Type == "递交材料不通过").Date;
            if (lst.Count(e => e.Type == "材料保存") > 0) FirstFielTime = lst.First(e => e.Type == "材料保存").Date;
            if ((State == 4 || State == 5 || State == 6 || State == 7) && !FirstFielTime.IsEmpty()) IsShowTime = 1;
            if (IsShowTime == 1)
            {
                Times = Time.GetWorkerDayNum(FirstFielTime.ToDate(), DateTime.Now);
                if (State == 7 && lst.Count(e => e.Type == "复审通过") > 0) Times = Time.GetWorkerDayNum(FirstFielTime.ToDate(), lst.First(e => e.Type == "复审通过").Date);
                if (Times == 0) Times = 1;
            }
            var Data = new
            {
                BillInfo = JSON["BillInfo"],
                MemberInfo = JSON["MemberInfo"],
                RoomList = JSON["RoomList"],
                ResidentList = JSON["ResidentList"],
                FileList = JSON["FileList"],
                CheckRecordList = JSON["CheckRecordList"],
                IsShowTime = IsShowTime,
                Times = Times
            };
            return Content(Data.ToJson());
        }

        /// <summary>
        /// 获取规则集合
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取规则集合", "GetMaterialList")]
        public ActionResult GetMaterialList(string keyValue, string MarryInfo, string HasLiveCard)
        {

            var materiallist = new MaterialRuleBLL().GetList();
            QualificationBillEntity entity = QFBbll.GetEntity(keyValue);
            var lst = QMRbll.GetList();
            MemberInfoEntity mentity = new MemberBLL().GetEntity(entity.MemberId);
            List<ResidentInfoEntity> RIList = QFBbll.GetResidentInfoList(keyValue).ToList();
            int MarryState = Convert.ToInt32(MarryInfo);
            int IsSon = RIList.Count(e => e.Relation.Contains("子女"));
            if (Convert.ToInt32(MarryInfo) == 1 && IsSon > 0) //未婚有子女
            {
                MarryState = 8;
            }
            if (Convert.ToInt32(MarryInfo) == 2 && IsSon > 0) //已婚有子女
            {
                MarryState = 3;
            }
            if (Convert.ToInt32(MarryInfo) == 3 && IsSon <= 0) //已离婚无子女
            {
                MarryState = 4;
            }
            if (Convert.ToInt32(MarryInfo) == 3 && IsSon > 0) //离婚有子女
            {
                MarryState = 5;
            }
            if (Convert.ToInt32(MarryInfo) == 4 && IsSon <= 0) //丧偶无子女
            {
                MarryState = 6;
            }
            if (Convert.ToInt32(MarryInfo) == 4 && IsSon > 0) //丧偶有子女
            {
                MarryState = 7;
            }
            lst = lst.Where(e => e.IsPermant == Convert.ToInt32(HasLiveCard) && e.MarrayInfo == MarryState).ToList();
            List<MaterialRuleEntity> MSlst = new List<MaterialRuleEntity>();
            var list = new MaterialSeedBLL().GetList().ToList();
            foreach (var item in lst)
            {
                MSlst.Add(materiallist.FirstOrDefault(e => e.Code == item.Materialld));
            }
            list = list.Where(e => e.BillCode == keyValue).ToList();
            if (list != null && list.Count > 0)
            {
                var data = from a in MSlst
                           join b in list on a.Code equals b.RuleCode into temp
                           from tt in temp.DefaultIfEmpty()
                           select new
                           {
                               a.Name,
                               a.IsSubmit,
                               a.IsUpload,
                               RuleCode = a.Code,
                               CommitState = tt == null ? 0 : tt.CreateDate != null ? 1 : 0,
                               UploadState = tt == null ? 0 : !string.IsNullOrEmpty(tt.FileUrl) ? 1 : 0,
                               Code = tt == null ? "" : tt.Code,
                               FileName = tt == null ? "" : tt.FileName,
                               FileUrl = tt == null ? "" : tt.FileUrl,
                               IsQualified = tt == null ? 0 : tt.IsQualified,
                               CreateDate = tt == null ? null : tt.CreateDate,
                               CreateUserName = tt == null ? "" : tt.CreateUserName,
                               ReceiveDate = tt == null ? null : tt.ReceiveDate,
                               ReceiveUserName = tt == null ? "" : tt.ReceiveUserName,
                               Memo = a.Memo,
                               BillCode = "",
                               Description = a.Description
                           };
                return Content(data.ToJson());
            }
            else
            {
                var data = from a in MSlst
                           select new
                           {
                               a.Name,
                               a.IsSubmit,
                               a.IsUpload,
                               RuleCode = a.Code,
                               CommitState = 0,
                               UploadState = 0,
                               Code = "",
                               FileName = "",
                               FileUrl = "",
                               IsQualified = 0,
                               CreateUserName = "",
                               ReceiveUserName = "",
                               Memo = a.Memo,
                               BillCode = "",
                               Description = a.Description
                           };
                return Content(data.ToJson());
            }
        }


        #endregion

        #region 保存数据
        /// <summary>
        /// 复审（提交）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="Type"> 1-审核申请人信息 2-材料递交 3-市局审批 4-受理中心复审</param>
        /// <param name="State">审核结果</param>
        /// <param name="Memo">不同过原因</param>
        /// <returns></returns> 
        [ValidateAntiForgeryToken]
        [HttpPost]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "复审（提交", "SubmitForm")]
        public ActionResult SubmitForm(string keyValue, string Type, string State, string Memo)
        {
            QualificationBillCheckRecordEntity entity = new QualificationBillCheckRecordEntity();
            switch (Type)
            {
                case "1":
                    entity.Type = 2;
                    break;
                case "2"://市局审批 
                    entity.Type = 3;
                    break;
                case "3"://受理中心复审
                    entity.Type = 4;
                    break;
                default:
                    break;
            }
            if (State == "0")
            {
                entity.CheckMemo = Memo;
            }
            entity.BillId = keyValue;
            entity.Category = 2;
            entity.CheckFlag = Convert.ToInt32(State);
            entity.CheckDate = DateTime.Now;
            entity.CheckMan = OperatorProvider.Provider.Current().UserName;
            entity.CheckManId = OperatorProvider.Provider.Current().UserId;
            entity.Date = DateTime.Now;
            try
            {
                QFBbll.CheckBillInfo(Convert.ToInt32(Type), entity);
                return Success("提交成功");
            }
            catch (Exception e)
            {
                return Error("操作失败" + e.Message);
            }
        }

        /// <summary>
        /// 材料提交审核
        /// </summary>
        /// <param name="keyValue">单据Id</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "材料提交审核", "SumbitFile")]
        public ActionResult SumbitFile(string keyValue, string lst, string State, string Memo, string CityBurceauCode)
        {

            List<MaterialSeedEntity> filelist = lst.ToList<MaterialSeedEntity>();
            QualificationBillCheckRecordEntity entity = new QualificationBillCheckRecordEntity();
            entity.BillId = keyValue;
            entity.Category = 2;
            entity.CheckDate = DateTime.Now;
            entity.CheckMan = OperatorProvider.Provider.Current().UserName;
            entity.CheckManId = OperatorProvider.Provider.Current().UserId;
            if (State == "0")
            {
                entity.CheckMemo = Memo;
            }
            entity.CheckFlag = Convert.ToInt32(State);
            entity.Date = DateTime.Now;
            entity.Type = 2;
            try
            {
                QFBbll.CheckFileInfo(keyValue, filelist, entity, CityBurceauCode);
                return Success("提交成功！");
            }
            catch (Exception e)
            {
                return Error("操作失败:" + e.Message);
            }

        }

        /// <summary>
        /// 材料保存
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="lst"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "材料保存", "SaveMater")]
        public ActionResult SaveMater(string keyValue, string lst)
        {
            try
            {
                List<MaterialSeedEntity> filelist = lst.ToList<MaterialSeedEntity>();
                QFBbll.SaveMater(keyValue, filelist);
                return Success("保存成功！");
            }
            catch (Exception e)
            {
                return Error("材料保存失败！" + e.Message);
                throw;
            }
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns> 
        public ActionResult UploadFile(string keyValue)
        {
            try
            {
                HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
                string imgPath = "/Resource/QualificationFile_" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string FileUrl = "";
                if (hfc != null && hfc.Count > 0)
                {
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        if (hfc[i].FileName == "") continue;
                        else
                        {
                            string FilePath = Server.MapPath(imgPath);
                            if (!Directory.Exists(FilePath))
                            {
                                Directory.CreateDirectory(FilePath);
                            }
                            hfc[i].SaveAs(FilePath + hfc[i].FileName);
                            FileUrl = URL != "" ? FilePath.Replace(HttpRuntime.AppDomainAppPath, URL) + hfc[i].FileName : FilePath + hfc[i].FileName;
                        }
                    }
                }
                return Success("操作成功。", keyValue + "," + FileUrl);
            }
            catch (Exception e)
            {
                return Error("附件上传失败：" + e.Message);
            }
        }

        /// <summary>
        /// 批量审批（指针对市局阶段）
        /// </summary> 
        /// <param name="State">1-通过  0-不通过</param>
        /// <param name="Data">单据编号集合</param>
        /// <param name="Memo">不通过原因</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存（提交）申请单", "SaveForm")]
        public ActionResult AllCheckInfo(string State, string Data, string Memo)
        {
            bool QuaCheckSecurity = LeSoft.Application.Bussiness.WorkRoleSettingBLL.GetIsAudit(Convert.ToInt32(LeSoft.Application.Code.WorkRoleEnum.QuaCheckSecurity));
            bool QuaCheckCenter = LeSoft.Application.Bussiness.WorkRoleSettingBLL.GetIsAudit(Convert.ToInt32(LeSoft.Application.Code.WorkRoleEnum.QuaCheckCenter));
            int S = Convert.ToInt32(State);
            try
            {
                if (QuaCheckSecurity == false && QuaCheckCenter == false) return Error("您不是该业务的处理人!");
                List<string> Codelst = Data.Split(',').ToList();
                foreach (var item in Codelst)
                {
                    QualificationBillEntity qety = QFBbll.GetEntity(item);
                    if (!qety.IsEmpty())
                    {
                        QualificationBillCheckRecordEntity entity = new QualificationBillCheckRecordEntity();
                        //市局审批
                        if (QuaCheckSecurity == true && qety.State == 5)
                        {
                            if (S == 0) entity.CheckMemo = Memo;
                            entity.BillId = qety.Id;
                            entity.Category = 2;
                            entity.CheckFlag = S;
                            entity.CheckDate = DateTime.Now;
                            entity.CheckMan = OperatorProvider.Provider.Current().UserName;
                            entity.CheckManId = OperatorProvider.Provider.Current().UserId;
                            entity.Date = DateTime.Now;
                            QFBbll.CheckBillInfo(2, entity);
                        }
                        //受理中心
                        if (QuaCheckCenter == true && qety.State == 6)
                        {
                            if (S == 0) entity.CheckMemo = Memo;
                            entity.BillId = qety.Id;
                            entity.Category = 2;
                            entity.CheckFlag = S;
                            entity.CheckDate = DateTime.Now;
                            entity.CheckMan = OperatorProvider.Provider.Current().UserName;
                            entity.CheckManId = OperatorProvider.Provider.Current().UserId;
                            entity.Date = DateTime.Now;
                            QFBbll.CheckBillInfo(3, entity);
                        }
                    }
                }
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error("批量操作失败:" + e.Message);
            }
        }
        #endregion


        #region 数据导出
        /// <summary>
        /// 资料导出
        /// </summary>
        public ActionResult GetExportList(string queryJson)
        {
            new ExportBLL().GetExportList((int)ExportType.ReQB, queryJson);
            return Success("导出成功。");
        }
        #endregion
    }
}
